package com.syqc.videos

import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.PopupWindow
import androidx.activity.viewModels
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import autodispose2.autoDispose
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.syqc.comlib.base.BaseActivity
import com.syqc.comlib.rx.filterFast
import com.syqc.entity.KeyValue
import com.syqc.monitor.R
import com.syqc.monitor.databinding.ActivityStopVideoBinding
import com.syqc.monitor.databinding.PopupPassViewBinding
import com.syqc.utils.Keys
import com.syqc.utils.UrlUtil
import com.syqc.videos.videomanager.TapeManager

/**
 *@author  hfjs
 *@time   2024/8/29 11:14
 *@desc
 */
class StopVideoActivity :
    BaseActivity<ActivityStopVideoBinding>(ActivityStopVideoBinding::inflate) {
    private val mViewModel: com.syqc.videos.StopPlayerVM by viewModels()
    private val mPopup by lazy {
        com.syqc.videos.PassPopup(this, mViewModel.videoPass) {
            mViewModel.channel = it.key
            binding.tvPass.text = it.value
            releasePlayer()
            binding.stopPlayer.setUp(
                mViewModel.getUrlTime(mViewModel.seekToTime),
                false,
                ""
            )
            binding.stopPlayer.startPlayLogic()
        }
    }

    override fun initView() {
        mViewModel.carId = intent.getStringExtra(Keys.INTENT_CAR_ID) ?: ""
        val videos = intent.getStringExtra(Keys.VIDEO)
        val startTime = intent.getStringExtra("startTime")
        val endTime = intent.getStringExtra("endTime")
        val plate = intent.getStringExtra(Keys.INTENT_PLATE) ?: ""
        binding.tvPlate.text = plate
        val passName = mViewModel.handleEntity(startTime!!, endTime!!, videos!!)
        binding.tvPass.text = passName
        initPlayer()
        initVM()

        binding.stopPlayer.setUp(
            mViewModel.getUrlTime(), false, ""
        )
        binding.stopPlayer.startPlayLogic()
        binding.root.postDelayed({
            if (mViewModel.videoPass.size <= 1) return@postDelayed
            if (!isFinishing && !mPopup.isShowing)
                mPopup.showAsDropDown(binding.tvPass)
        }, 200)
    }

    override fun setListener() {
        binding.tvPass.filterFast {
            if (mViewModel.videoPass.size <= 1) return@filterFast
            if (!isFinishing && !mPopup.isShowing)
                mPopup.showAsDropDown(binding.tvPass)
        }
        binding.ivBAck.filterFast {
            finish()
        }
    }

    private fun initPlayer() {
        binding.stopPlayer.setSeekBarState(mViewModel.maxTime)

        binding.stopPlayer.setVideoAllCallBack(object : GSYSampleCallBack() {
            override fun onPlayError(url: String?, vararg objects: Any?) {
                super.onPlayError(url, *objects)
                releasePlayer()
                mViewModel.getErrorState()
            }

            override fun onPrepared(url: String?, vararg objects: Any?) {
                super.onPrepared(url, *objects)
                binding.stopPlayer.startTime()
            }
        })

        binding.stopPlayer.setTmnListener(object : com.syqc.videos.interfaces.ITmnListener {
            override fun onProgress(progress: Long) {
                if (progress >= mViewModel.maxTime) {
                    releasePlayer()
                }
            }

            override fun onSeekProgress(progress: Long) {
                if (progress >= mViewModel.maxTime) {
                    releasePlayer()
                } else {
                    releasePlayer()
                    mViewModel.setSeekTime(progress)
                    binding.stopPlayer.setSeekBarProgress(progress, mViewModel.maxTime)
                    binding.stopPlayer.setUp(
                        mViewModel.getUrlTime(mViewModel.seekToTime),
                        false,
                        ""
                    )
                    binding.stopPlayer.startPlayLogic()
                }
            }

            override fun onMultipleListener(multiple: Int) {
                mViewModel.multipleVideo(multiple)
            }

            override fun onPlayState(type: com.syqc.videos.interfaces.PlayState) {
                when (type) {
                    com.syqc.videos.interfaces.PlayState.PAUSE -> mViewModel.pauseVideo()
                    com.syqc.videos.interfaces.PlayState.FAST -> mViewModel.fastVideo()
                    com.syqc.videos.interfaces.PlayState.BACK -> mViewModel.backVideo()
                    com.syqc.videos.interfaces.PlayState.FRAME -> mViewModel.frameVideo()
                }
            }

            override fun onBackListener() {
                destroy()
                finish()
            }

            override fun onPlaying(isPlaying: Boolean) {
                if (isPlaying) {
                    binding.stopPlayer.showProgress(false)
                    mViewModel.pauseVideo()
                } else {
                    if (mViewModel.videoType == 0) {
                        binding.stopPlayer.setUp(mViewModel.getUrlTime(), false, "")
                        binding.tvPlatToast.isGone = true
                        binding.stopPlayer.showProgress(false)
                        binding.stopPlayer.startPlayLogic()
                    } else {
                        mViewModel.resumeVideo()
                    }
                }
            }
        })
    }

    private fun initVM() {
        mViewModel.toastObserver().autoDispose(scopeProvider).subscribe(this::toastObserver)

        mViewModel.videoToastLive.observe(this) {
            binding.stopPlayer.showProgress(false)
            binding.tvPlatToast.text = UrlUtil.getToastMap()[it ?: "88"]
            binding.stopPlayer.release()
            binding.tvPlatToast.isVisible = true
            binding.stopPlayer.showStartPlay(false)
        }

        mViewModel.videoStateLive.observe(this) {
            when (it) {
                //暂停
                1 -> {
                    binding.stopPlayer.gsyVideoManager.player.pause()
                }

                //恢复播放
                5 -> {
                    binding.stopPlayer.gsyVideoManager.player.start()
                    mViewModel.multiple = 1
                }
                //拖动播放 、关闭
                else -> {}
            }
        }
    }

    /**
     * 重置播放
     *
     */
    private fun releasePlayer() {
        mViewModel.stopPlay()
        binding.stopPlayer.run {
            release()
            onVideoReset()
            setSeekBarState(mViewModel.maxTime)
            showStartPlay(true)
        }
        TapeManager.instance.releaseMediaPlayer()
    }

    /**
     * 销毁
     */
    private fun destroy() {
        mViewModel.stopPlay()
        binding.stopPlayer.stopTime()
        binding.root.postDelayed({
            binding.stopPlayer.release()
            TapeManager.instance.releaseMediaPlayer()
        }, 100)
    }

    override fun onDestroy() {
        super.onDestroy()
        destroy()
    }

    override fun onPause() {
        super.onPause()
        binding.stopPlayer.onVideoPause()
    }

    override fun onResume() {
        super.onResume()
        binding.stopPlayer.onVideoResume()
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        window.decorView.systemUiVisibility =
            View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                    View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
    }
}

class PassPopup(
    private val context: Context,
    private val passs: MutableList<KeyValue>,
    private val callback: (KeyValue) -> Unit
) :
    PopupWindow() {
    val binding = PopupPassViewBinding.inflate(LayoutInflater.from(context))
    private val mAdapter by lazy { com.syqc.videos.PassAdapter() }

    init {
        contentView = binding.root
        isClippingEnabled = false //设置是否裁剪内容
        isFocusable = true //popupwindow设置焦点
        setBackgroundDrawable(ColorDrawable(0)) //设置背景
//        isOutsideTouchable = true //点击外面窗口消失
        width = LinearLayout.LayoutParams.WRAP_CONTENT //设置SelectPicPopupWindow弹出窗体的宽
        height = LinearLayout.LayoutParams.WRAP_CONTENT //设置SelectPicPopupWindow弹出窗体的高
        initView()
    }

    private fun initView() {
        binding.rvPass.layoutManager = LinearLayoutManager(context)
        binding.rvPass.adapter = mAdapter
        mAdapter.setList(passs)
        mAdapter.setOnItemClickListener { adapter, view, position ->
            callback(mAdapter.data[position])
            dismiss()
        }
    }
}

class PassAdapter : BaseQuickAdapter<KeyValue, BaseViewHolder>(R.layout.item_pass_video) {
    override fun convert(holder: BaseViewHolder, item: KeyValue) {
        holder.setText(R.id.tvPass, item.value)
    }
}